<!DOCTYPE html>



  


<html class="theme-next pisces use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="函数备忘," />





  <link rel="alternate" href="/atom.xml" title="伏窗尾的猫" type="application/atom+xml" />






<meta name="description" content="函数体文件io打开文件：int open(const char *pathname, int flags, mode_t mode);  读取文件：ssize_t read(int fd, void *buf, size_t count);  写入文件：ssize_t write(int fd, const void *buf, size_t count);  光标移动：off_t lseek(i">
<meta name="keywords" content="函数备忘">
<meta property="og:type" content="article">
<meta property="og:title" content="代码备忘录">
<meta property="og:url" content="http://bclnc.github.io/2019/03/04/代码备忘录/index.html">
<meta property="og:site_name" content="伏窗尾的猫">
<meta property="og:description" content="函数体文件io打开文件：int open(const char *pathname, int flags, mode_t mode);  读取文件：ssize_t read(int fd, void *buf, size_t count);  写入文件：ssize_t write(int fd, const void *buf, size_t count);  光标移动：off_t lseek(i">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2021-01-12T16:56:25.439Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="代码备忘录">
<meta name="twitter:description" content="函数体文件io打开文件：int open(const char *pathname, int flags, mode_t mode);  读取文件：ssize_t read(int fd, void *buf, size_t count);  写入文件：ssize_t write(int fd, const void *buf, size_t count);  光标移动：off_t lseek(i">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":true,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://bclnc.github.io/2019/03/04/代码备忘录/"/>





  <title>代码备忘录 | 伏窗尾的猫</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">伏窗尾的猫</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://bclnc.github.io/2019/03/04/代码备忘录/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="喵呜">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/1.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="伏窗尾的猫">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">代码备忘录</h1>
        

        <div class="post-meta">
		
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2019-03-04T20:37:24+08:00">
                2019-03-04
              </time>
            

            
              <span class="post-meta-divider">|</span>
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-check-o"></i>
              </span>
              
                <span class="post-meta-item-text">更新于&#58;</span>
              
              <time title="更新于" itemprop="dateModified" datetime="2021-01-13T00:56:25+08:00">
                2021-01-13
              </time>
            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/学习之路/" itemprop="url" rel="index">
                    <span itemprop="name">学习之路</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          
             <span id="/2019/03/04/代码备忘录/" class="leancloud_visitors" data-flag-title="代码备忘录">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">热度&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
				 <span>℃<span>
             </span>
          

          

		  
			  <span class="post-meta-divider">|</span>
			  <span id="busuanzi_value_page_pv"></span>次阅读
		  
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h2 id="函数体"><a href="#函数体" class="headerlink" title="函数体"></a>函数体</h2><h3 id="文件io"><a href="#文件io" class="headerlink" title="文件io"></a>文件io</h3><pre><code>打开文件：int open(const char *pathname, int flags, mode_t mode);

读取文件：ssize_t read(int fd, void *buf, size_t count);

写入文件：ssize_t write(int fd, const void *buf, size_t count);

光标移动：off_t lseek(int fd, off_t offset, int whence);

关闭文件：close（fd）；

内存映射：void *mmap(void *addr, size_t length, int prot, int flags,int fd, off_t offset);

解除映射：int munmap(void *addr, size_t length);
</code></pre><p>详解在本文。</p>
<h3 id="进程"><a href="#进程" class="headerlink" title="进程"></a>进程</h3><pre><code>创建进程：pid_t fork(void);
获取本身ID：pid_t getpid(void);  
获取父进程ID：pid_t getppid(void);
进程退出：void exit(int status)；//status存返回值,会刷新流
进程退出：void _exit(int status)//不会刷新流，立即返回给内核
等待子进程状态改变：pid_t wait(int *status);
等待指定进程状态改变：pid_t waitpid(pid_t pid, int *status, int options);
执行指定命令或程序：pid_t waitpid(pid_t pid, int *status, int options);
</code></pre><p>详解请见<a href="https://eidolon.xyz/2018/09/20/%E5%AD%A6%E4%B9%A0%E4%B9%8B%E8%B7%AF%E2%80%94%E2%80%94%E8%BF%9B%E7%A8%8B/" target="_blank" rel="noopener">进程</a></p>
<h3 id="进程间通信"><a href="#进程间通信" class="headerlink" title="进程间通信"></a>进程间通信</h3><h4 id="管道："><a href="#管道：" class="headerlink" title="管道："></a>管道：</h4><pre><code>创建无名管道：int pipe(int pipefd[2]);//全双工，有亲缘关系使用
创建有名管道：int mkfifo(const char *pathname, mode_t mode);
删除有名管道：int unlink(const char *path);
</code></pre><h4 id="信号："><a href="#信号：" class="headerlink" title="信号："></a>信号：</h4><pre><code>绑定指定信号和函数：sighandler_t signal(int signum, sighandler_t handler);
等待一个信号：int pause(void);
发送一个信号：int kill(pid_t pid, int sig);
</code></pre><h4 id="消息队列："><a href="#消息队列：" class="headerlink" title="消息队列："></a>消息队列：</h4><pre><code>创建IPC对象的key：key_t ftok(const char *pathname, int proj_id);//通信的话key要相同
创建或打开消息队列：int msgget(key_t key, int msgflg);
发送信息：int msgsnd(int msqid, const void *msgp, size_t msgsz, int msgflg);
接收信息：ssize_t msgrcv(int msqid, void *msgp, size_t msgsz, long msgtyp,int msgflg);
消息队列操作：msgctl(int msqid, int cmd, struct msqid_ds *buf);
</code></pre><h4 id="共享内存："><a href="#共享内存：" class="headerlink" title="共享内存："></a>共享内存：</h4><pre><code>创建key：key_t ftok(const char *pathname, int proj_id);//通信的话key要相同
创建或打开一个共享内存：int shmget(key_t key, size_t size, int shmflg);    
映射：void *shmat(int shmid, const void *shmaddr, int shmflg);    
解映射：int shmdt(const void *shmaddr);    
共享内存操作：int shmctl(int shmid, int cmd, struct shmid_ds *buf);
</code></pre><h4 id="信号量："><a href="#信号量：" class="headerlink" title="信号量："></a>信号量：</h4><p>保护共享资源，实现“同步”，“互斥”。当资源需要保护的时候创建。</p>
<pre><code>创建信号量id：int semget(key_t key, int nsems, int semflg);
信号量操作：int semctl(int semid, int semnum, int cmd, ...);

pv操作结构体：

struct sembuf{
unsigned short sem_num;
short          sem_op;
short          sem_flg;
}
操作函数：int semop(int semid, struct sembuf *sops, unsigned nsops);
p操作：
struct sembuf sops;
sops.sem_num = 0;//指定第0个信号量！
sops.sem_op = 1;
sops.sem_flg = SEM_UNDO;
ret = semop(sem_id, &amp;sops,1);
v操作：
sops.sem_num = 0;//指定第0个信号量！
sops.sem_op = -1;
sops.sem_flg = SEM_UNDO;
ret = semop(sem_id, &amp;sops,1);
</code></pre><p>详情请见：<a href="https://eidolon.xyz/2018/09/28/%E5%AD%A6%E4%B9%A0%E4%B9%8B%E8%B7%AF%E2%80%94%E2%80%94%E8%BF%9B%E7%A8%8B%E9%97%B4%E9%80%9A%E4%BF%A1/" target="_blank" rel="noopener">进程间通信</a></p>
<h3 id="线程"><a href="#线程" class="headerlink" title="线程"></a>线程</h3><pre><code>创建一个线程：int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
                          void *(*start_routine) (void *), void *arg);
线程自杀：void pthread_exit(void *retval);
线程他杀：int pthread_cancel(pthread_t thread);
线程属性设置：int pthread_setcancelstate(int state, int *oldstate);
等待线程退出：int pthread_join(pthread_t thread, void **retval);
设置线程分离属性：int pthread_detach(pthread_t thread);
</code></pre><h3 id="线程间通信"><a href="#线程间通信" class="headerlink" title="线程间通信"></a>线程间通信</h3><pre><code>互斥锁创建：int pthread_mutex_init(pthread_mutex_t *restrict mutex,
                        const pthread_mutexattr_t *restrict attr);
互斥锁销毁：int pthread_mutex_destroy(pthread_mutex_t *mutex);
P操作:int pthread_mutex_lock(pthread_mutex_t *mutex);
非阻塞P操作：int pthread_mutex_trylock(pthread_mutex_t *mutex);
v操作：int pthread_mutex_unlock(pthread_mutex_t *mutex);
</code></pre><p>详情请见：<a href="https://eidolon.xyz/2019/03/05/%E8%BF%9B%E7%A8%8B%E4%B8%8E%E7%BA%BF%E7%A8%8B%E2%80%94%E2%80%94%E5%9B%9B/" target="_blank" rel="noopener">线程</a></p>
<h2 id="文件IO"><a href="#文件IO" class="headerlink" title="文件IO"></a>文件IO</h2><h3 id="打开-关闭：open-close函数"><a href="#打开-关闭：open-close函数" class="headerlink" title="打开/关闭：open/close函数"></a>打开/关闭：open/close函数</h3><p>头文件：</p>
<pre><code>#include &lt;sys/types.h&gt;
#include &lt;sys/stat.h&gt;
#include &lt;fcntl.h&gt;
</code></pre><p>int open(const char *pathname, int flags, mode_t mode);</p>
<pre><code>    第一个参数：需要打开或者创建文件的路径。
    第二个参数：flags 打开的标志位。
            O_RDONLY  只读打开
            O_WRONLY  只写打开
            O_RDWR      读写打开

            上面这三个标志位，只能选其中一个，除了这三个之外，还可以和下面的一些标志组合起来使用。
            O_APPEND  追加的方式打开。
            O_CREAT   创建标志，如果文件不存在可以创建它。
            O_EXCL    一般这个标志位和O_CREAT组合起来使用，O_CREAT  | O_EXCL 如果文件已存在
                  open就会出错，并且错误码是 errno == EEXIST
            O_TRUNC      假如文件存在并且是一个普通文件，打开的方式是 O_RDWR 或者 O_WRONLY。
                  就会把文件里面的内容清空掉。

    **如果需要创建的方式打开一个文件，就需要第三个参数，否则不需要第三个参数
    第三个参数：如果文件不存在，需要创建一个文件的时候，需要指定文件的属性
        属性包含了：当前用户的权限，组用户的权限，其他用户的权限
            权限：可读 ---&gt;4
                  可写 ---&gt;2
                  可执行--&gt;1
8进制：如0666；
</code></pre><p>关闭函数：close（fd）；</p>
<p>fd为open函数的返回值。</p>
<h3 id="操作（读、写）read-write函数"><a href="#操作（读、写）read-write函数" class="headerlink" title="操作（读、写）read/write函数"></a>操作（读、写）read/write函数</h3><pre><code>#include &lt;unistd.h&gt;
</code></pre><p>ssize_t read(int fd, void *buf, size_t count);</p>
<pre><code>第一个参数：是打开的文件描述符。就是前面用open函数打开返回的值，就是文件描述符。
第二个参数： void *buf，这个void可以代表任意你需要的类型，将数据读到这个buf所指向的内存空间。
第三个参数：count 以字节来计算，要读多少个字节。

返回值：成功返回的是实际读到的数据的字节数，这个返回值有可能比请求读取的字节数要少，但是并不是出错了，可能是
    实际没有那么多数据可读。
</code></pre><p>ssize_t write(int fd, const void *buf, size_t count);</p>
<pre><code>第一个参数：是打开的文件描述符。就是前面用open函数打开返回的值，就是文件描述符。
第二个参数： void *buf，这个void可以代表任意你需要的类型，将buf所指向的内存空间的数据写入到fd所指向的
        文件或者设备

第三个参数：count 以字节来计算，要写多少个字节。

返回值：成功返回的是实际写入数据的字节数，这个返回值有可能比请求写入的字节数要少，但是并不是出错了，可能是
    实际没有足够的空间可写。
    如果出错的话，返回-1，并且错误码会被设置。
</code></pre><h3 id="文件定位-：lseek函数"><a href="#文件定位-：lseek函数" class="headerlink" title="文件定位 ：lseek函数"></a>文件定位 ：lseek函数</h3><pre><code>#include &lt;sys/types.h&gt;
#include &lt;unistd.h&gt;
</code></pre><p><strong>off_t lseek(int fd, off_t offset, int whence);</strong></p>
<pre><code>第一个参数：我们打开文件对应的文件描述符。
第二个参数：相对于第三个参数的偏移量，这个偏移量可正可负。正表示往前移动读写位置，负表示往后面移动读写位置。

第三个参数：定位的位置：
        SEEK_SET：把读写位置定位到开头，如果offset=0；
        SEEK_END：把读写位置定位到末尾，如果offset=0；
        SEEK_CUR：把读写位置定位到当前，如果offset=0；


返回值：如果成功，返回的是当前的位置按字节来计算距离文件开始的位置的距离。
</code></pre><h3 id="内存映射"><a href="#内存映射" class="headerlink" title="内存映射"></a>内存映射</h3><pre><code>#include &lt;sys/mman.h&gt;
</code></pre><p>void <em>mmap(void </em>addr, size_t length, int prot, int flags,int fd, off_t offset);</p>
<pre><code>第一个参数：你要映射到进程的哪一个虚拟地址空间。设置为空: NULL，系统会自动给你分配一个可用的地址。
第二个参数：需要映射的空间的大小，需要是4K的倍数。（4096）。
第三个参数：这个参数指定这一块内存空间访问的权限。（要和打开的文件权限一致）

    PROT_EXEC  Pages may be executed. 可执行权限
    PROT_READ  Pages may be read.      可读权限
    PROT_WRITE Pages may be written.  可写权限
    PROT_NONE  Pages may not be accessed.没有访问的权限。

第四个参数：flags，映射的标志。

    MAP_SHARED ： 共享映射，对其他进程可见，对这个映射区的操作会同步到对应的文件或者驱动。


    MAP_PRIVATE ： 私有映射，对其他进程来说不可见，开辟了一个私有的空间，对这个区域的操作，不会同步到对应的
            文件或者驱动。

第五个参数：就是我们前面打开的文件或者设备对应返回的fd。

第六个参数：偏移量。表示要从文件的哪个位置开始映射。offset也必须是4k的整数倍。通常设置为0。

返回值：如果映射成功，返回的是一个指针，这个指针指向这个映射区
    如果映射失败了，返回 MAP_FAILED (这个东西就是===&gt; (void *) -1)


int munmap(void *addr, size_t length);
第一个参数：要解除映射的地址。（这个地址指的是前面映射成功返回的地址）
第二个参数：就是申请映射的长度。
</code></pre>
      
    </div>
    
    
    
	
	<div>
	  
		<div>
    
        <div style="text-align:center;color: #ccc;font-size:14px;">------ 本文结束------</div>
    
</div>
	  
	</div>
	

    

    

    
      <div>
        <ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者：</strong>
    喵呜  |  喵呜
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="http://bclnc.github.io/2019/03/04/代码备忘录/" title="代码备忘录">http://bclnc.github.io/2019/03/04/代码备忘录/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>
    本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/3.0/" rel="external nofollow" target="_blank">CC BY-NC-SA 3.0</a> 许可协议。转载请注明出处！
  </li>
  <li class="post-copyright-license">
    并保留本声明和上方二维码。感谢您的阅读和支持！
  </li>
</ul>
      </div>
    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/函数备忘/" rel="tag"># 函数备忘</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2019/02/28/排序算法/" rel="next" title="排序算法">
                <i class="fa fa-chevron-left"></i> 排序算法
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2019/03/05/进程与线程——四/" rel="prev" title="进程与线程——线程">
                进程与线程——线程 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/images/1.jpg"
                alt="喵呜" />
            
              <p class="site-author-name" itemprop="name">喵呜</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">21</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index-1.html">
                  <span class="site-state-item-count">5</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

			
			  <div class="site-state-item site-state-tags">
				<a href="/tags/ || tags">
				  <span class="site-state-item-count">13</span>
				  <span class="site-state-item-name">标签</span>
				</a>
			  </div>
			

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#函数体"><span class="nav-text">函数体</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#文件io"><span class="nav-text">文件io</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#进程"><span class="nav-text">进程</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#进程间通信"><span class="nav-text">进程间通信</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#管道："><span class="nav-text">管道：</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#信号："><span class="nav-text">信号：</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#消息队列："><span class="nav-text">消息队列：</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#共享内存："><span class="nav-text">共享内存：</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#信号量："><span class="nav-text">信号量：</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#线程"><span class="nav-text">线程</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#线程间通信"><span class="nav-text">线程间通信</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#文件IO"><span class="nav-text">文件IO</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#打开-关闭：open-close函数"><span class="nav-text">打开/关闭：open/close函数</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#操作（读、写）read-write函数"><span class="nav-text">操作（读、写）read/write函数</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#文件定位-：lseek函数"><span class="nav-text">文件定位 ：lseek函数</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#内存映射"><span class="nav-text">内存映射</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      
        <div class="back-to-top">
          <i class="fa fa-arrow-up"></i>
          
        </div>
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">喵呜</span>

  
</div>

<div>
<script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>
<span id="busuanzi_container_site_pv" style='display:none'>
    本站总访问量 <span id="busuanzi_value_site_pv"></span> 次
    <span class="post-meta-divider">|</span>
</span>
<span id="busuanzi_container_site_uv" style='display:none'>
    有<span id="busuanzi_value_site_uv"></span>人看过我的博客啦
</span>
</div>


  <div class="powered-by">QQ  母胎solo </div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">微信：请勿撩骚 &mdash;  v5.1.4</div>




        







        
      </div>
    </footer>

    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  











  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  

  
  
    <script type="text/javascript" src="/lib/canvas-nest/canvas-nest.min.js"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("C4C53NNHHx80rdEcr9XGvVER-gzGzoHsz", "onx6D9nlRn56BhlHoI3E08PQ");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  

  
  

  

  

  
  <script type="text/javascript" src="/js/src/exturl.js?v=5.1.4"></script>


  <!-- 页面点击小红心 -->
<script type="text/javascript" src="/js/src/love.js"></script>

</body>
</html>
